package com.mattidroid.spiegel;

import java.util.Locale;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class SingleWebView extends Activity implements OnGestureListener {
// public class SingleWebView extends Activity {
	
	boolean localSwipe = false;
	
	static final int CALL_SETTINGS = 222;
	static final int CALL_AboutPage = 444;

	static final int VISIBLE = 0;
	static final int INVISIBLE = 4;
	static final int GONE = 8;
	
	int swipeHorizontalSensitivity = 50;
    
    String MyUrl;

	// read locale settings from prefs and set accordingly
	void setLocale () {
		
		//Dynamic Override system settings LOCALE 
		//Need in all Classes
		GlobalClass GlobalData = ((GlobalClass)getApplicationContext());
	    String languageToLoad  = GlobalData.isLocaleString(GlobalData.overrideLocale);
	    GlobalClass.log(false, "SingleWebViewsetLocale Locale Setting to : " + languageToLoad);
	    
	    if (languageToLoad.equals("")) {
	    	// do nothing
	    	 GlobalClass.log(false, "applicationInit.setLocale Locale EMPTY");
	    }
	    else {
	    	//Override system settings LOCALE
		    Locale locale = new Locale(languageToLoad); 
		    Locale.setDefault(locale);
		    Configuration config = new Configuration();
		    config.locale = locale;
		    getBaseContext().getResources().updateConfiguration(config, 
		    getBaseContext().getResources().getDisplayMetrics());
	    } 
	}
    
	void InitURL () {
		
		// read the parameter given from start activity
		Bundle bundle = this.getIntent().getExtras();
		MyUrl = bundle.getString("url");
		GlobalClass.log(false, "WebView InitURL Bundle: " + MyUrl);
	}
	
	WebView myOwnWebView;						// Webview handle
	ProgressDialog MyProgressDialog;			// Dialog ontop of Webview "Lade Daten.."
	View SpinnerOverlayView;					// View for Spinner Overlay
	LayoutInflater SpinnerOverlayLayout = null;	// Inflater for Spinner Layout
	
	void toggleSpinner(boolean action){

		if (action) {
			// GlobalClass.log ("WebView.toggleSpinner - Spinner ON");
			// spinner in header line
			// getParent().setProgressBarIndeterminateVisibility(true);
			// set Spinner on XML Overlay invisible 
			SpinnerOverlayView.setVisibility(VISIBLE);
		}
		else {
			// GlobalClass.log ("WebView.toggleSpinner - Spinner OFF");
			// spinner in header line
			// getParent().setProgressBarIndeterminateVisibility(false);
			// Set Spinner on XML Overlay visible
			SpinnerOverlayView.setVisibility(GONE);
		}

	}
	
	// definition to change tab in tabhost
	Intent intent;
	
	/* Only if implements OnGestureListener
	 * http://www.ceveni.com/2009/08/android-gestures-detection-sample-code.html
	*/
	   private static final int SWIPE_MIN_DISTANCE = 120;
	   private static final int SWIPE_MAX_OFF_PATH = 250;
	   private static final int SWIPE_THRESHOLD_VELOCITY = 200;


	   private GestureDetector gestureScanner;
	 
	   // Need to override dispatchTouchEvent to catch onFling with my handler
	   @Override 
	   public boolean dispatchTouchEvent(MotionEvent screenEventMotion){ 
		   if (localSwipe == true) {
			   super.dispatchTouchEvent(screenEventMotion);
			   return gestureScanner.onTouchEvent(screenEventMotion); 
		   } else { 
			   return super.dispatchTouchEvent(screenEventMotion); 
		   }
	   } 
	   
	   @Override
	   public boolean onTouchEvent(MotionEvent screenEventMotion)
	   {
		   GlobalClass.log(false, "onTouchEvent: " + screenEventMotion);	   
		   return gestureScanner.onTouchEvent(screenEventMotion);
		   // return super.onTouchEvent(screenEventMotion);
	   }
	   
	   @Override
	   public boolean onDown(MotionEvent screenEventMotion)
	   {
	    	 GlobalClass.log(false, "onDown: " + screenEventMotion);
	    	 // return super.onTouchEvent(screenEventMotion);
	    	 // return gestureScanner.onTouchEvent(screenEventMotion);
	    	 // return this.onDown(screenEventMotion);
	    	 return true;
	   }
	   
	   @Override
	   public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
	   {
	       try {
	           if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
	               return false;
	           
	           // right to left swipe
	           if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) 
	           {
	               Toast.makeText(getApplicationContext(), "Right 2 Left Swipe", Toast.LENGTH_SHORT).show();
	               GlobalClass.log(true, "onFling + Right 2 Left Swipe ");
	               // TODO: Prevent a full reload, just switch tabs
	                 Bundle MyBundle = new Bundle();
			    	 this.finish();
			    	 Intent myIntent = new Intent(this, applicationInit.class);   	 
			    	 MyBundle.putInt("page", 1);
			    	 myIntent.putExtras(MyBundle);
			 		 startActivity(myIntent);
			 	   //
	           }  
	           
	           else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	               Toast.makeText(getApplicationContext(), "Left 2 Right Swipe", Toast.LENGTH_SHORT).show();
	               GlobalClass.log(true, "onFling + Left 2 Right Swipe ");	 
	               // TODO: Prevent a full reload, just switch tabs
	                 Bundle MyBundle = new Bundle();
			    	 this.finish();
			    	 Intent myIntent = new Intent(this, applicationInit.class);   	 
			    	 MyBundle.putInt("page", -1);
			    	 myIntent.putExtras(MyBundle);
			 		 startActivity(myIntent);
			 	   //
	           }
	           
	           else if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	               // Toast.makeText(getApplicationContext(), "Swipe up", Toast.LENGTH_SHORT).show();
	               GlobalClass.log(false, "onFling + Up Swipe ");	
	           }  
	           
	           else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
	               // Toast.makeText(getApplicationContext(), "Swipe down", Toast.LENGTH_SHORT).show();
	               GlobalClass.log(false, "onFling + Down Swipe ");          
	           }
	       } 
	       
	       catch (Exception e) 
	       {
	           // nothing
	       }
	               return true;
	   }
	     
	   @Override
	   public void onLongPress(MotionEvent screenEventMotion)
	   {
	    	 GlobalClass.log(false, "onLongPress: " + screenEventMotion);
	   }
	   
	   @Override
	   public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
	   {
		   // GlobalClass.log(true, "onScroll ");	   
		   return true;
	   }
	   
	   @Override
	   public void onShowPress(MotionEvent screenEventMotion)
	   {
		   GlobalClass.log(false, "onShowPress " + screenEventMotion);
	   }         
	   
	   @Override
	   public boolean onSingleTapUp(MotionEvent screenEventMotion)       
	   {
		   GlobalClass.log(false, "onShowPress " + screenEventMotion);
		   return true;
	   }
	// EOI
	
	// Disabled: Catch swipe with TOUCH event - WORKS,NOT THAT GREAT
	/*
	@Override
    public boolean onTouchEvent(MotionEvent screenEventMotion) {

		
		// pointer to globalClass
		GlobalClass GlobalData = ((GlobalClass)getApplicationContext());
		GlobalClass.log(true, "onTouch Event: " + screenEventMotion);
		
		// only execute if swipe is enabled in settings
		if (GlobalData._isSwipeOn == 1)
		{
		
			 // To tell SingleWebView in MotionEvent what to do
			 // Bundle MyBundle = new Bundle();
			 
		     final int historySize = screenEventMotion.getHistorySize();
		     final int pointerCount = screenEventMotion.getPointerCount();
		     
		     float startX = 0;
		     float startY = 0;
		     float endX = 0;
		     float endY = 0;
		     
		     Bundle MyBundle = new Bundle();
		     
		     GlobalClass.log(false, "Test - TouchEvent PointerCount: " + pointerCount);
		     GlobalClass.log(false, "Test - TouchEvent HistorySize: " + historySize);
		     
		     //Most Touch Event to not generate more than one pointer !!!
		     for (int h = 0; h < historySize; h++) {
		    	 
		         for (int p = 0; p < pointerCount; p++) {
		        	 GlobalClass.log(false, "TouchEvent Start: " + screenEventMotion.getHistoricalX(p, h)  + " - " +  screenEventMotion.getHistoricalY(p, h));
		        	 startX = screenEventMotion.getHistoricalX(p, h);
		        	 startY = screenEventMotion.getHistoricalY(p, h);
		         }
		     }
		     
		     for (int p = 0; p < pointerCount; p++) {
		    	 GlobalClass.log(false, "TouchEvent End: "  +  screenEventMotion.getX(p)  + " - " +  screenEventMotion.getY(p));
		    	 endX = screenEventMotion.getX(p);
		    	 endY = screenEventMotion.getY(p);
		     }
		     
		     GlobalClass.log(false, "Swipe StartY: " + startY + " EndY : " + endY + " Length Y: " + (startY - endY) );
		     GlobalClass.log(false, "Swipe StartX: " + startX + " EndX : " + endX + " Length X: " + (startX - endX) );
		     
		     // Detect a horizontal swipe
		     if ( ((startY-endY) < swipeHorizontalSensitivity ) && ((startY-endY) > -swipeHorizontalSensitivity) ) {
		    	 
		    	 
		    	// Detect a swipe from	 right to left
		    	if (startX > endX) {
			    	 
			    	 // Action after swipe event	  
			    	 GlobalClass.log(true, "onTouchEvent R2L Swipe");
			    	 // Toast.makeText(getApplicationContext(), "Swipe R2L Length: " + (endX - startX ) , Toast.LENGTH_SHORT).show();
			    	 this.finish();
			    	 Intent myIntent = new Intent(this, applicationInit.class);   	 
			    	 MyBundle.putInt("page", 1);
			    	 myIntent.putExtras(MyBundle);
			 		 startActivity(myIntent);
			    	 
		    	}
			     // Detect a swipe from left to right
		    	if (startX < endX) {
	
			    	 // Action after swipe event
		    		GlobalClass.log(true, "onTouchEvent L2R Swipe");
			    	 // Toast.makeText(getApplicationContext(), "Swipe L2R Length: " + (startX - endX ) , Toast.LENGTH_SHORT).show();	
			    	 this.finish();
			    	 Intent myIntent = new Intent(this, applicationInit.class);	    	 	    	 
			    	 MyBundle.putInt("page", -1);
			    	 myIntent.putExtras(MyBundle);
			 		 startActivity(myIntent);	
	
		    	}	    	 
		     }
		}
		
        return super.onTouchEvent(screenEventMotion);
    } 
    */
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && myOwnWebView.canGoBack()) {
        	toggleSpinner(true);
        	myOwnWebView.goBack();
            return true;
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) &! myOwnWebView.canGoBack()) {
        	// Abfangen wenn auf Startseite, dann Dialog Sicherheitsabfrage  	
        	AlertClass AreYouSure = new AlertClass(this);
        	AreYouSure.show(); 	
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }   
    
    private class MyWebWrapperClient extends WebViewClient {
    	@Override        
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);    
            toggleSpinner(true);
            GlobalClass.log (false, "WebView.shouldOverrideUrlLoading");
            return true;
        }
    }

    public void onCreate(Bundle savedInstanceState) { 
    	
        super.onCreate(savedInstanceState);
        GlobalClass GlobalData = ((GlobalClass)getApplicationContext());  
        GlobalClass.log(false, "SingelWebView.onCreate");
       
        // for touchEvent to support onFling
       	gestureScanner = new GestureDetector(this);
        if (GlobalData._isSwipeOn == 1)
        {
        	localSwipe = true;
        	GlobalClass.log(true, "onCreate Swipe = " + localSwipe );
        }
        
        InitURL();
        
	    // read locale settings from prefs and set accordingly
	    setLocale();
        
        //XML Layouts amd actual webview identifier
        setContentView(R.layout.webview_layout);  
        myOwnWebView = (WebView) findViewById(R.id.webview_xmlview);                       
        
        setContentView(myOwnWebView);
      
        myOwnWebView.getSettings().setJavaScriptEnabled(true);       
        myOwnWebView.getSettings().setSupportZoom(true);         
        myOwnWebView.getSettings().setBuiltInZoomControls(true); 
                
        // Progress Dialog ontop of view
        MyProgressDialog = new ProgressDialog(this);      
        MyProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        MyProgressDialog.setCancelable(true);
        MyProgressDialog.setMessage(this.getString(R.string.load_page));
        MyProgressDialog.show();

        // For Spinner create a Overlay View
        SpinnerOverlayLayout = LayoutInflater.from(getBaseContext());
        SpinnerOverlayView = SpinnerOverlayLayout.inflate(R.layout.spinner_overlay, null);
        LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        this.addContentView(SpinnerOverlayView, layoutParamsControl);
        SpinnerOverlayView.setVisibility(GONE);
  
        // Spinner an
        toggleSpinner(true);
        
        // Try to add gestures as overlay - parameter for show gestures etc. missing
        // GlobalClass.log("onCreate addGestureOverlay INIT");
        // GestureOverlayLayout = LayoutInflater.from(getBaseContext());
        // GestureOverlayView = GestureOverlayLayout.inflate(R.layout.gesture_overlay, null);
        // LayoutParams GestureParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        // this.addContentView(GestureOverlayView, GestureParamsControl);
        
        // Need to add a handler for gesture overlay
        // GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.webview_gestures);
        // gestures.addOnGesturePerformedListener((OnGesturePerformedListener) this);
               
        myOwnWebView.setWebChromeClient(new WebChromeClient() {
       	
        public void onProgressChanged(WebView view, int progress) {
       	     	
            if(progress == 100) {
            	MyProgressDialog.dismiss();
                toggleSpinner(false);
            }
          }
        });

        myOwnWebView.setWebViewClient(new WebViewClient() {
          public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
          }
        });

        myOwnWebView.loadUrl(MyUrl);
        myOwnWebView.setWebViewClient(new MyWebWrapperClient());
    }
      
	public void callBack_Home() {
		toggleSpinner(true);
		myOwnWebView.loadUrl(MyUrl);
	}
    
	public void callUpdate_Content(){
		toggleSpinner(true);
		myOwnWebView.reload(); 
	}	
	
	public void callAbout(){
		// Old About Dialog with Message box
		/*
		DialogClass aboutDialog = new DialogClass(this);
		aboutDialog.show();
		*/
		// New About Page
		Intent myIntent = new Intent(this, ShowAboutPage.class);
		startActivityForResult(myIntent,CALL_AboutPage);	
	}
	
	public void callShow_Options(){
		Intent myIntent = new Intent(this, EditSettings.class);
		startActivityForResult(myIntent,CALL_SETTINGS);	
	}	

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	GlobalClass.log(false, "SingelWebView.onCreateOptionsMenu");
    	setLocale();
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_option_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.about:
        	callAbout();
            return true;  
        case R.id.back_home:
        	callBack_Home();
            return true;         
        case R.id.update_content:
        	callUpdate_Content();
            return true;           
        case R.id.show_options:
        	callShow_Options();
            return true;     
        case R.id.quit:
        	System.exit(0);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }  
}	

